package seatiger.tomcat.catalina.util;

import seatiger.tomcat.catalina.Lifecycle;
import seatiger.tomcat.catalina.LifecycleEvent;
import seatiger.tomcat.catalina.LifecycleListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 事件管理类
 */
final public class LifecycleSupport {
    /**
     * 帮助哪个生命周期器管理事件
     */
    private Lifecycle lifecycle;

    /**
     * 有哪些事件监听器
     */
    private List<LifecycleListener> listeners = new ArrayList<>();

    public LifecycleSupport(Lifecycle lifecycle){
        this.lifecycle = lifecycle;
    }

    /**
     * 添加时间监听器
     */
    public void addLifecycleListener(LifecycleListener listener){
        synchronized (listeners){
            listeners.add(listener);
        }
    }

    public void removeLifecycleListener(LifecycleListener listener){
        synchronized (listeners){
            listeners.remove(listener);
        }
    }

    public List<LifecycleListener> findLifecycleListeners(){
        return listeners;
    }

    public void fireLifecycleEvent(String type, Object data){
        LifecycleEvent event = new LifecycleEvent(lifecycle,type,data);
        listeners.forEach(listener -> listener.lifecycleEvent(event));
    }
}
